package com.sxt.demo.djiapplication.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import com.sxt.demo.djiapplication.databinding.ActivityWayPointLoadBinding
import com.yanzhenjie.recyclerview.SwipeRecyclerView

import android.view.ViewGroup

import com.yanzhenjie.recyclerview.SwipeMenuItem

import androidx.recyclerview.widget.LinearLayoutManager

import android.graphics.Color
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.sxt.demo.djiapplication.DjiDemoApplication
import com.sxt.demo.djiapplication.R
import com.sxt.demo.djiapplication.common.CommonConstants
import com.sxt.demo.djiapplication.dao.WayPointRecordItemDao
import com.sxt.demo.djiapplication.dao.WayPointRecordService
import com.sxt.demo.djiapplication.databinding.RecordListItemLayoutBinding
import com.sxt.demo.djiapplication.entity.WayPointRecord
import com.sxt.demo.djiapplication.utils.ToastUtils
import com.xuexiang.xui.widget.actionbar.TitleBar
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration


class WayPointLoadActivity : BaseActivity() {

    private val binding by lazy { ActivityWayPointLoadBinding.inflate(layoutInflater) }

    private val mRecyclerView: SwipeRecyclerView by lazy { binding.srvRecordList }

    private lateinit var mAdapter: RecordListAdapter

    private val wayPointRecordService by lazy {
        DjiDemoApplication.getSingleObj(
            WayPointRecordService::class.java
        )
    }

    private var currentPage = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
    }

    override fun init(bundle: Bundle?) {
        initAdapter(getWayPointRecordList())
    }

    override fun addListener() {
        binding.tbRecordListActionBar.setLeftClickListener {
            exitActivity()
        }
        binding.tbRecordListActionBar.addAction(object :
            TitleBar.TextAction(getString(R.string.clear_all)) {
            override fun performAction(view: View?) {
                val rs = wayPointRecordService.clear()
                if (rs) {
                    val oldSize = mAdapter.dataList.size
                    mAdapter.dataList = ArrayList(emptyList())
                    mAdapter.notifyItemRangeRemoved(0, oldSize)
                    ToastUtils.show(
                        this@WayPointLoadActivity,
                        getString(R.string.clear_result, getString(R.string.success))
                    )
                } else {
                    ToastUtils.show(
                        this@WayPointLoadActivity,
                        getString(R.string.clear_result, getString(R.string.failed))
                    )
                }
            }
        })
    }

    override fun exitActivity() {
        finish()
    }

    private fun initAdapter(dataList: List<WayPointRecord>) {
        // 初始化
        doInit(dataList)

        // 设置侧滑菜单
        setSwipeMenu()

        // item点击的监听
        setItemClickListener()

        // 设置刷新和加载更多
        setRefreshAndLoadMore()

        mRecyclerView.adapter = mAdapter
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setRefreshAndLoadMore() {
        val srlArea = binding.srlArea
        // 下拉刷新
        srlArea.setOnRefreshListener {
            currentPage = 1
            val (data, success) = wayPointRecordService.queryByOffset(desc = true)
            if (success) {
                mAdapter.dataList = ArrayList(data)
                mAdapter.notifyDataSetChanged()
            }
            it.finishRefresh(success)
        }
        // 加载更多
        srlArea.setOnLoadMoreListener {
            val (data, success) = wayPointRecordService.queryByOffset(++currentPage, desc = true)
            if (success) {
                if (data.isNotEmpty()) {
                    val dataList = mAdapter.dataList
                    dataList.addAll(data)
                    mAdapter.notifyItemRangeChanged(dataList.size - data.size, data.size)
                } else {
                    ToastUtils.show(this, "没有更多数据了...")
                }
            }
            it.finishLoadMore(success)
        }
    }

    private fun setItemClickListener() {
        mRecyclerView.setOnItemClickListener { _, adapterPosition ->
            val intent = Intent(CommonConstants.LOAD_WAYPOINT_BROADCAST)
            intent.putExtra("id", mAdapter.dataList[adapterPosition].id)
            sendBroadcast(intent)
            finish()
        }
    }

    private fun doInit(dataList: List<WayPointRecord>) {
        mAdapter = RecordListAdapter(ArrayList(dataList))
        mRecyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerView.addItemDecoration(
            DefaultItemDecoration(
                // 可兼容的getColor方法
                ContextCompat.getColor(
                    this,
                    R.color.qmui_config_color_gray_8
                )
            )
        )
    }

    private fun setSwipeMenu() {
        // 定义菜单选项
        mRecyclerView.setSwipeMenuCreator { _, rightMenu, _ ->
            val deleteItem = SwipeMenuItem(this)
            deleteItem.setBackgroundColor(Color.parseColor("#FF3D39"))
                .setText("删除")
                .setTextColor(Color.WHITE)
                .setHeight(ViewGroup.LayoutParams.MATCH_PARENT).width = 170
            rightMenu.addMenuItem(deleteItem)
        }

        //菜单点击监听
        mRecyclerView.setOnItemMenuClickListener { menuBridge, adapterPosition ->
            menuBridge.closeMenu()
            if (menuBridge.direction == SwipeRecyclerView.RIGHT_DIRECTION) {
                // 删除操作
                if (menuBridge.position == 0) {
                    val rs = wayPointRecordService.callInTx {
                        val id = mAdapter.dataList[adapterPosition].id
                        it.wayPointRecordDao.deleteByKey(id)
                        it.wayPointRecordItemDao.queryBuilder().where(
                            WayPointRecordItemDao.Properties.RecordId.eq(id)
                        ).buildDelete().executeDeleteWithoutDetachingEntities()
                        true
                    }
                    if (rs) {
                        mAdapter.dataList.removeAt(adapterPosition)
                        mAdapter.notifyItemRemoved(adapterPosition)
                    } else {
                        ToastUtils.show(this, "删除失败")
                    }
                }
            }
        }
    }

    private fun getWayPointRecordList(): List<WayPointRecord> {
        currentPage = 1
        return wayPointRecordService.queryByOffset(desc = true).first
    }

    private inner class RecordListAdapter(
        /**
         * 数据集
         */
        var dataList: ArrayList<WayPointRecord>

    ) : RecyclerView.Adapter<RecordListItemViewHolder>() {

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): RecordListItemViewHolder {
            return RecordListItemViewHolder(
                RecordListItemLayoutBinding.inflate(
                    layoutInflater,
                    parent,
                    false
                )
            )
        }

        override fun onBindViewHolder(holder: RecordListItemViewHolder, position: Int) {
            val data = dataList[position]
            holder.tvTitle.text = data.title
            holder.tvTime.text = data.recordTime
        }

        override fun getItemCount(): Int {
            return dataList.size
        }
    }

    private inner class RecordListItemViewHolder(
        binding: RecordListItemLayoutBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        val tvTitle: TextView = binding.tvTitle

        val tvTime: TextView = binding.tvTime

    }
}